<template>
    <div style="">
        <Header :left="true" leftText="返回" title="异常让步生产申请"> </Header>
        <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
            left-icon="description">异常让步生产申请</NoticeBar>


        <van-form :style="autoHeight" @submit="onSubmit">
            <van-field readonly class="formstyle" style="font-weight: bold" name="picker" :value="showOrder" label="生产订单"
                placeholder="点击选择生产订单" show-word-limit type="text" v-if="orderStatus != 1" rows="2" autosize />

            <van-field class="formstyle" readonly :value="form.MaterialID" v-if="orderStatus != 1" name="物料号" label="物料代码"
                placeholder="输入物料代码" />
            <van-field readonly class="formstyle" :value="form.MaterialName" name="物料名称" label="物料名称"
                v-if="orderStatus != 1" placeholder="输入物料名称" />

            <van-field readonly class="formstyle" required :value="showShift" name="班次" label="班次" placeholder="请选择班次"
                :rules="[{ required: true, message: '班次不能为空' }]" autosize />

            <van-field readonly required class="formstyle" :value="showFactory" name="工厂代码" label="工厂代码"
                placeholder="点击选择工厂代码" show-word-limit :rules="[{ required: true, message: '工厂代码不能为空' }]" rows="2"
                autosize />

            <van-field required readonly class="formstyle" :value="showMachine" name="设备代码" label="设备代码" show-word-limit
                :rules="[{ required: true, message: '设备代码不能为空' }]" rows="2" autosize placeholder="选择设备代码" />

            <van-field readonly required class="formstyle" v-model="showAbn" name="异常类型" label="异常类型" placeholder="选择异常类型"
                :rules="[{ required: true, message: '异常类型不能为空' }]" show-word-limit rows="2" autosize
                @click="showPickerNoticeMemo = true" />

            <NoticeBar color="#1989fa" background="#ecf9ff" style="margin-top: 5px; font-size: 15px; font-weight: bold"
                left-icon="description">异常信息</NoticeBar>
            <van-field readonly class="formstyle" :value="form.RealtimeMsgID" name="实时消息ID" label="实时消息ID"
                placeholder="实时消息ID" show-word-limit rows="2" autosize />
            <van-field readonly class="formstyle" :value="form.FailCode" name="故障代码" label="故障代码" placeholder="故障代码"
                show-word-limit rows="2" autosize v-if="status == 0" />
            <van-field readonly class="formstyle" :value="showOTime" name="异常发生时间" label="异常发生时间" placeholder="选择异常发生时间"
                show-word-limit :rules="[{ required: true, message: '异常发生时间不能为空' }]" rows="2" autosize />

            <van-field readonly class="formstyle" :value="showCtime" name="让步生产截止时间" label="让步生产截止时间" placeholder="让步生产截止时间"
                show-word-limit :rules="[{ required: true, message: '让步生产截止时间不能为空' }]" @click="showTimePicker = true"
                rows="2" autosize />

            <van-popup v-model="showTimePicker" position="bottom">
                <van-datetime-picker v-model="pickerTime" type="datetime" :min-date="minDate"
                    @confirm="confirmCompleteDatetime" title="让步生产截止时间" />
            </van-popup>
            <van-field readonly class="formstyle" v-model="form.DataCollectionItemID" name="异常参数代码" label="异常参数代码"
                placeholder="异常参数代码" show-word-limit rows="2" autosize />


            <van-field readonly class="formstyle" :value="form.DataCollectionItemName" name="异常参数名称" label="异常参数名称"
                placeholder="异常参数名称" show-word-limit rows="2" autosize />

            <van-field readonly class="formstyle" :value="form.FactValue" name="数采项实际值" label="数采项实际值" placeholder="数采项实际值"
                show-word-limit rows="2" autosize />


            <van-field readonly class="formstyle" :value="form.AbnormalLevl" name="故障等级" label="故障等级" placeholder="故障等级"
                show-word-limit rows="2" autosize v-if="status == 0" />

            <van-field readonly class="formstyle" :value="form.HighLevel" name="数采项上限" label="数采项上限" placeholder="数采项上限"
                show-word-limit rows="2" autosize v-if="status == 2" />

            <van-field readonly class="formstyle" :value="form.LowLevel" name="数采项下限" label="数采项下限" placeholder="数采项下限"
                show-word-limit rows="2" autosize v-if="status == 2" />
            <van-field required class="formstyle" rows="4" autosize type="textarea" maxlength="100"
                v-model="form.RequestMemo" name="申请理由" label="申请理由" placeholder="输入申请理由"
                :rules="[{ required: true, message: '申请理由不能为空' }]" />

            <div style="margin: 16px">
                <van-button color="#138087" round block type="info" native-type="submit">保存</van-button>
            </div>
        </van-form>
    </div>
</template>
  
<script>
import {
    Col,
    Row,
    Form,
    Cell,
    Icon,
    Field,
    NumberKeyboard,
    Image as VanImage,
    Picker,
    popup,
    SubmitBar,
    Button,
    Loading,
    Overlay,
    Dialog,
    Toast,
    NoticeBar,
    Tag,
    DatetimePicker,
    ImagePreview,
    CellGroup,
    Uploader,
    Cascader,
    Calendar,
    RadioGroup,
    Radio,
    Divider,
    Stepper,
    AddressList,
    Checkbox,
    CheckboxGroup,

} from "vant";


import "vue-easytable/libs/themes-base/index.css";
import { VTable } from "vue-easytable";
import { _httpClient } from "@/libs/apisie";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { getToken, getBaseApiFrefix } from "@/libs/auth";
import Header from "@/components/header.vue";
import { storage } from "@/libs/utils";


Vue.use(Form);
Vue.use(Field);
Vue.use(Overlay);
Vue.use(Loading);
Vue.use(Picker);
Vue.use(popup);
Vue.use(SubmitBar);
Vue.use(VanImage);
Vue.use(DatetimePicker);
Vue.use(Cascader);
Vue.use(Calendar);
Vue.use(Cell);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(Divider);
Vue.use(Stepper);
Vue.use(Button);
Vue.use(AddressList);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Col);
Vue.use(Row);

export default {
    name: "abnormalconcessioncreate",
    components: {
        Form,
        Row,
        Col,
        Button,
        Header,
        Form,
        Cell,
        Icon,
        Field,
        NumberKeyboard,
        Dialog,
        Toast,
        NoticeBar,
        Row,
        Tag,
        popup,
        DatetimePicker,
        ImagePreview,
        CellGroup,
        Uploader,
        Col,
        Calendar,
        Cascader,
        Picker,
        RadioGroup,
        Radio,
        Divider,
        Stepper,
        VTable,
        AddressList,
        Checkbox,
        CheckboxGroup,
    },
    data() {
        return {
            query: {
                QProblemName: "",
            },
            //orderList
            status: 0,
            orderStatus: 0,
            showPickerPOrderID: false,
            showCtime: null,
            pickerTime: null,
            minDate: new Date(),
            columnsPOrderIDND: [],
            columnsPOrderID: [],
            showOrder: "",
            searchKey1: "",
            //FACTORY
            showPickerFactoryID: false,
            columnsFactoryIDND: [{ FactoryName: "太仓工厂", FactoryID: "TC00", FactoryIDAndFactoryName: "TC00 太仓工厂" }],
            FactoryID: "TC00",
            showFactory: "TC00 太仓工厂",
            //ShiftID
            showPickerPShiftID: false,
            columnsPShiftIDND: [],
            showShift: "",
            //showMachine
            showMachine: "",
            //showTimePicker
            showTimePicker: false,
            showOTime: null,
            item: null,
            //NoticeMemo
            showNMeno: "",
            showPickerNoticeMemo: false,
            columnsQProblem: [],
            result: [],
            showAbn: "",
            columnsMachineEquipment: [],

            currentdate: new Date(),
            nowDate: null,
            showProductionDate: false,
            showProDatetimeFrom: false,
            showProDatetimeTo: false,
            showQProblemID: false,
            showPickerpMachineEquipmentID: false,
            user: [],
            form: {
                //申请理由
                Id: 0,
                MachineID: "",
                PShiftID: "",
                POrderID: "",
                MaterialID: "",
                MaterialName: "",
                OccurDatetime: "",
                CompleteDatetime: "",
                AbnormalTypeID: "",
                AbnormalDescription: "",
                RequestMemo: "",
                AbnormalLevl: "",
                FactoryID: "TC00",
                DataCollectionItemID: "",
                DataCollectionItemName: "",
                FailCode: "",
                LowLevel: 0,
                HighLevel: 0,
                FactValue: 0,
                RealtimeMsgID: 0,
                Creator: "",
                CreateDatetime: "",
                PrdChecked: false,
                PrdAgree: false,
                PrdCheckedDatetime: "",
                PrdCheckedMan: "",
                PrdCheckedMemo: "",
                FactoryManagerChecked: false,
                FactoryManagerAgree: false,
                FactoryManagerCheckedDatetime: "",
                FactoryManagerCheckedMan: "",
                FactoryManagerCheckedMemo: "",
                Token: ""
            },
        };
    },
    created: function () {

        this.user = JSON.parse(storage.get("user"));
        this.user.userId = this.user.userName;
        let item = api.pageParam.item
        this.item = item
        //alert(JSON.stringify(item))
        this.form.POrderID = item.POrderID

        this.form.PLineID = item.PLineID
        this.form.MachineID = item.MachineID
        let now = this.getNowTimepl()
        this.minDate = new Date()
        this.form.OccurDatetime = now
        this.showOTime = now
        this.getPOrderID()
        this.getMachineEquipment();
        // this.getNowTimeToSecond(); //进入页面调用该方法获取当前时间
        // //获取班次信息
        this.getshift();

        this.parseMsg(item)

        this.getQualityProblems();

    },
    mounted() {

    },

    destroyed() {
        clearInterval(this.nowtimer);
        this.nowDate = null;
    },
    watch: {  //实时监听搜索输入内容

        'searchKey1': {
            handler(newVal) {
                let key = String(newVal);
                //alert(key);
                key = key.replace(/\s*/g, "");
                const reg = new RegExp(key, "ig");
                /* 进行筛选，将筛选后的数据放入新的数组中，‘name’键可根据需要搜索的key进行调整 */
                this.columnsPOrderIDND = this.columnsPOrderID.filter(item => item.POrderIDAndMaterialName.match(reg) != null);
                //alert(this.searchColumns);
            },
            deep: true,
            immediate: true,
        }
    },

    methods: {
        confirmCompleteDatetime(value) {
            // alert(value)

            // alert("-----")
            this.showCtime = this.formatDate(value)
            // alert("-----")
            this.form.CompleteDatetime = value
            // alert("-----")
            this.showTimePicker = false

            // this.showOTime=this.formatDate(value)
            // this.form.OccurDatetime=value
            // this.showTimePicker=false
        },
        getNowTimepl() {
            let dateTime;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
            let ss =
                new Date().getSeconds() < 10
                    ? "0" + new Date().getSeconds()
                    : new Date().getSeconds();
            dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
            return dateTime;
        },
        handleSearchNations() { },
        showOrderSelect() {
            if (this.orderStatus == 1) {
                this.showPickerPOrderID = true
            }
        },
        async onSubmit() {
            var _this = this;
            Toast.loading({
                mask: true,
                forbidClick: true,
                duration: 0,
                message: "请稍等...",
            });

            try {
                this.form.AbnormalDescription = this.form.RequestMemo
                this.form.Id = 0
                this.form.Creator = this.user.userName;
                this.form.CreateDatetime = new Date()
                this.form.CompleteDatetime = this.showCtime;
                //alert(JSON.stringify(this.form));
                let res = await _httpClient.post(
                    _httpClient.getApiPrefix() + "/ProductionCompromiseRequest/SaveEntity",
                    {
                        body: this.form,
                    }
                );
                if (res.Message != null) {
                    //message不为空,有报错信息，打卡失败 暂时这样判断
                    Toast.clear();
                    Toast.fail("保存失败,请核对信息！");
                } else {
                    //打卡成功

                    Toast.clear();
                    Toast.success("保存成功！");

                    this.$ac.sendEvent({
                        name: 'flush-list'
                    });

                    //修正信息
                    // alert(JSON.stringify(_this.item))
                    await _httpClient.post(
                        _httpClient.getApiPrefix() + "/MessageReceived/ProcessEventMessage",
                        {
                            body: _this.item,
                        }
                    );

                    setTimeout(function () {
                        _this.$ac.closeWin();
                    }, 1000);
                }
            } catch (e) {
                Toast.fail(JSON.stringify(e));
            }
        },

        //获取班次信息
        async getshift() {
            let _this = this;
            try {
                let res = await _httpClient.get(
                    _httpClient.getApiPrefix() +
                    "/ProductionShift/GetCurrentPShiftBeginEnd?FactoryID=" +
                    _this.FactoryID
                );
                if (res.HttpCode === "200") {
                    let s = res.Data.split(";")
                    this.form.PShiftID = s[s.length - 1]

                    let res2 = await _httpClient.get(_httpClient.getApiPrefix() + "/ProductionShift/GetEntityName?FieldValue=" + this.form.PShiftID)
                    if (res2.HttpCode == 200) {
                        this.showShift = this.form.PShiftID + " " + res2.Data
                    }

                }
            } catch (e) {
                Toast.fail(JSON.stringify(e));
            }
        },


        onConfirmPShiftID(value, index) {
            this.showShift = this.columnsPShiftIDND[index].pshiftname
            this.form.PShiftID = this.columnsPShiftIDND[index].pShiftID;
            this.BeginTime = this.columnsPShiftIDND[index].BeginTime;
            this.showPickerPShiftID = false;
        },

        //获取缺陷原因
        async getQualityProblems() {
            if (this.item.EventTypeID.startsWith("CA")) {
                this.showAbn = "生产条件异常"
                this.form.AbnormalTypeID = "AT01"
            }
            if (this.item.EventTypeID.startsWith("MF")) {
                this.showAbn = "机器设备异常"
                this.form.AbnormalTypeID = "AT02"
            }
            if (this.item.EventTypeID.startsWith("TF")) {
                this.showAbn = "工艺参数异常"
                this.form.AbnormalTypeID = "AT03"
            }

        },

        onConfirmNoticeMemo(value, index) {
            this.showNMeno = this.columnsQProblem[index].pShow;
            this.form.AbnormalTypeID = this.columnsQProblem[index].AbnormalTypeID;
            this.showPickerNoticeMemo = false;
        },



        //获取设备信息
        async getMachineEquipment() {
            let _this = this;
            try {

                let res = await _httpClient.get(
                    _httpClient.getApiPrefix() + "/MachineEquipment/GetList?MachineID=" + this.form.MachineID
                );
                if (res.HttpCode === "200") {

                    this.showMachine = res.Data[0].MachineName + " " + res.Data[0].MachineID

                }
            } catch (e) {
                alert((JSON.stringify(e)));
            }
        },

        onConfirmpMachineEquipmentID(value, index) {
            this.showMachine = this.columnsMachineEquipment[index].pShow
            this.form.MachineID = this.columnsMachineEquipment[index].pMachineID;
            this.showPickerpMachineEquipmentID = false;
        },

        onConfirmProductionDate(time) {
            this.tempTime = time;
            //date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); // 时区补偿
            this.form.ProductionDate = `${time.getFullYear()}-${time.getMonth() + 1
                }-${time.getDate()}`;
            this.showProductionDate = false;
        },
        onConfirmProDatetimeFrom(time) {
            this.tempTime = time;
            //date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); // 时区补偿
            this.form.ProDatetimeFrom = `${time.getFullYear()}-${time.getMonth() + 1
                }-${time.getDate()} ${time.getHours().toString().padStart(2, 0)}:${time
                    .getMinutes()
                    .toString()
                    .padStart(2, 0)}`;
            this.showProDatetimeFrom = false;
        },
        onConfirmProDatetimeTo(time) {
            this.tempTime = time;
            //date.setMinutes(date.getMinutes() - date.getTimezoneOffset()); // 时区补偿
            this.form.ProDatetimeTo = `${time.getFullYear()}-${time.getMonth() + 1
                }-${time.getDate()} ${time.getHours().toString().padStart(2, 0)}:${time
                    .getMinutes()
                    .toString()
                    .padStart(2, 0)}`;
            this.showProDatetimeTo = false;
        },
        // 获取当前时间 yy-mm-dd hh:mf:ss
        getNowTimeToSecond() {
            let dateTime;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
            let ss =
                new Date().getSeconds() < 10
                    ? "0" + new Date().getSeconds()
                    : new Date().getSeconds();
            dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
            this.nowDate = dateTime;
            return dateTime;
        },
        // 获取当前时间 yy-mm-dd
        formatDate(date) {
            let dateTime;
            let yy = date.getFullYear();
            let mm = date.getMonth() + 1;
            let dd = date.getDate();
            let hh = date.getHours();
            let mf =
                date.getMinutes() < 10
                    ? "0" + date.getMinutes()
                    : date.getMinutes();
            let ss =
                date.getSeconds() < 10
                    ? "0" + date.getSeconds()
                    : date.getSeconds();
            dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
            this.nowDate = dateTime;
            return dateTime;
        },
        //time
        onconfirmTime(value) {

            this.showOTime = this.formatDate(value)
            this.form.OccurDatetime = value
            this.showTimePicker = false
        },


        //orderList
        onConfirmPOrderID(value, index) {
            this.showOrder = this.columnsPOrderIDND[index].POrderIDAndMaterialName;
            this.form.POrderID = this.columnsPOrderIDND[index].POrderID;
            this.form.MaterialName = this.columnsPOrderIDND[index].MaterialName
            this.form.MaterialID = this.columnsPOrderIDND[index].MaterialID
            this.showPickerPOrderID = false;
        },
        async getPOrderID() {
            //让给用户选择
            if (this.form.POrderID == null || this.form.POrderID == "" || this.form.POrderID == undefined) {
                this.orderStatus = 1

                return
            }

            try {
                //alert(this.form.POrderID)

                let res = await _httpClient.get(
                    _httpClient.getApiPrefix() + "/ProductionOrder/GetList?POrderID=" + this.form.POrderID
                );


                if (res.HttpCode === "200") {
                    this.form.MaterialName = res.Data[0].MaterialName
                    this.form.MaterialID = res.Data[0].MaterialID
                    this.showOrder = res.Data[0].POrderID + " " + res.Data[0].MaterialName
                }

            } catch (e) {
                alert(JSON.stringify(e));
            }
        },

        // factory
        onConfirmFactoryID(value, index) {
            this.showFactory = this.this.columnsFactoryID[index].FactoryName
            this.form.FactoryID = this.columnsFactoryID[index].FactoryID;
            this.showPickerFactoryID = false;
        },
        async getFactoryID() {

            let _this = this;
            try {
                // alert(_httpClient.getApiPrefix() )
                let res = await _httpClient.get(
                    _httpClientApisie.getApiPrefix() + "/OrganizationManage/Factory/GetPageListJson?pageSize=10&pageIndex=1&sort=Id&sortType=desc"
                );
                // alert(JSON.stringify(res))
                if (res.HttpCode === "200") {
                    let teamMap = res.Data.map((item) => ({
                        FactoryID: item.FactoryID,
                        FactoryName: item.FactoryName,

                        FactoryIDAndFactoryName: item.POrderID + " " + item.FactoryName,
                    }));
                    _this.columnsFactoryID = teamMap;
                    _this.columnsFactoryIDND = teamMap;
                }

            } catch (e) {
                alert(JSON.stringify(e));
            }
        },
        dealtxt(val) {
            let s1 = val.split("产品");
            let s2 = s1[1].split(",在机台");
            //alert(s2[0].indexOf(",") != -1);
            if (s2[0].indexOf(",") != -1) {
                let s3 = s2[0].replace(/,/g, " ");
                let s4 = s1[0] + "产品" + s3 + ",在机台" + s2[1];
                return s4;
            }
            else {
                return val;
            }
        },
        parseMsg(item) {
            //alert(JSON.stringify(item));
            //alert(item.EventTypeID);
            try {
                if ((item.EventTypeID).startsWith("TF")) {
                    this.status = 2
                    let msg = item.MessageContent;

                    let msp = this.dealtxt(msg).split(",");

                    //alert(msp);
                    //alert(JSON.stringify(msp));
                    this.form.DataCollectionItemName = msp[2].split("<")[1].split("-")[1].split(">")[0];
                    //alert(this.form.DataCollectionItemName);
                    this.form.DataCollectionItemID = msp[2].split("<")[0].split(":")[1];
                    //alert(this.form.DataCollectionItemName);
                    this.form.RealtimeMsgID = item.MessageID;
                    //alert(this.form.RealtimeMsgID);
                    this.form.FactValue = msp[2].split("为")[1];
                    //alert(this.form.FactValue);

                    // alert(msg.split("[")[1].split(",")[0])
                    this.form.LowLevel = parseFloat(msg.split("[")[1].split(",")[0]);
                    // alert(this.form.LowLevel);
                    this.form.HighLevel = parseFloat(msg.split("[")[1].split(",")[1].split("]")[0]);
                    //alert(this.form.HighLevel);
                }

                // mf
                if ((item.EventTypeID).startsWith("MF")) {
                    this.status = 0
                    let msg = item.MessageContent
                    let msp = (msg).split(",");

                    if (msp[0].includes("A类")) {
                        this.form.AbnormalLevl = 'A'
                    }
                    if (msp[0].includes("B类")) {
                        this.form.AbnormalLevl = 'B'
                    }
                    if (msp[0].includes("C类")) {
                        this.form.AbnormalLevl = 'C'
                    }
                    if (msp[0].includes("D类")) {
                        this.form.AbnormalLevl = 'D'
                    }

                    let code = msp[1].split("，")[0].split("：")[1]
                    this.form.FailCode = code
                    this.form.FactValue = code
                    this.form.DataCollectionItemName = msp[1].split("，")[1].split("：")[1].split(".")[0]
                    this.form.DataCollectionItemID = msp[0].split("，")[1].split("：")[1]
                    this.form.RealtimeMsgID = item.MessageID
                }

                //CA
                if ((item.EventTypeID).startsWith("CA")) {
                    let msg = item.MessageContent
                    let msp = (msg).split(",")
                    // alert(JSON.stringify(msp))
                    if (msg.includes("<")) {
                        this.status = 1
                        this.form.DataCollectionItemName = "<" + msp[2].split("<")[1].split("！")[0].split(".")[0]
                        this.form.DataCollectionItemID = msp[2].split("<")[0].split(":")[1]
                        this.form.RealtimeMsgID = item.MessageID
                        this.form.FactValue = msp[2].split("为")[1]
                    } else {
                        this.status = 2
                        let a = msp[0].split("传感器")[1]
                        this.form.DataCollectionItemName = a.split("车间-")[1].split("-")[0] + "传感器"
                        this.form.DataCollectionItemID = a.split("-")[0] + "-" + a.split("-")[1]
                        this.form.RealtimeMsgID = item.MessageID
                        this.form.FactValue = msp[0].split("：")[1].split("超")[0]
                        this.form.LowLevel = parseFloat(msp[0].split("[")[1])
                        this.form.HighLevel = parseFloat(msp[1].split("]")[0])
                    }
                }
            } catch (e) {
                alert(JSOn.stringify(e))
            }
            //tf
        }
    },

};
</script>
  
<style>
body {
    background-color: white;
}
</style>
  